package com.zyk.scaffold.tcp.holder;

import com.zyk.scaffold.tcp.components.PersistentLayerComponent;
import com.zyk.scaffold.tcp.connector.TcpConnectionManager;
import com.zyk.scaffold.tcp.disruptor.DisruptorTask;
import com.zyk.scaffold.tcp.propertises.TcpProperties;
import com.zyk.scaffold.tcp.proto3.MessageBuf;
import com.zyk.scaffold.tcp.server.handler.MsgHandler;
import com.zyk.scaffold.tcp.session.SessionManager;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;
    private static TcpProperties tcpProperties = null;
    private static DisruptorTask disruptorTask = null;
    private static TcpConnectionManager tcpConnectionManager = null;
    private static SessionManager sessionManager = null;
    private static PersistentLayerComponent persistentLayerComponent = null;
    private static Map<MessageBuf.JMTransfer.MsgType, MsgHandler> mapRequestType2requestHandler = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ContextHolder.applicationContext = applicationContext;
        ContextHolder.tcpProperties = applicationContext.getBean(TcpProperties.class);
        ContextHolder.disruptorTask = applicationContext.getBean(DisruptorTask.class);
        ContextHolder.persistentLayerComponent = applicationContext.getBean(PersistentLayerComponent.class);
        ContextHolder.tcpConnectionManager = applicationContext.getBean(TcpConnectionManager.class);
        ContextHolder.sessionManager = applicationContext.getBean(SessionManager.class);
        applicationContext.getBeansOfType(MsgHandler.class).values().forEach(item -> mapRequestType2requestHandler.put((MessageBuf.JMTransfer.MsgType)item.getRequestType(), item));
    }

    public static DisruptorTask getDisruptorTask() {
        return ContextHolder.disruptorTask;
    }

    public static PersistentLayerComponent getPersistentLayerComponent() {
        return persistentLayerComponent;
    }

    public static MsgHandler getMsgHandler(MessageBuf.JMTransfer.MsgType requestType) {
        return mapRequestType2requestHandler.get(requestType);
    }

    public static TcpConnectionManager getTcpConnectionManager() {
        return tcpConnectionManager;
    }

    public static TcpProperties getTcpProperties() {
        return tcpProperties;
    }

    public static SessionManager getSessionManager() {
        return sessionManager;
    }
}
